package at.ac.tuwien.swa.sparrow.server.conf

import at.ac.tuwien.swa.sparrow._
import at.ac.tuwien.swa.sparrow.common._
import at.ac.tuwien.swa.sparrow.server.persistence._
import com.google.common.net.HostAndPort
import java.util.UUID
import java.util.concurrent.atomic.AtomicLong
import javax.annotation.PostConstruct
import javax.inject.Inject
import org.springframework.stereotype.Component
import scala.io.Source
import scala.util.Properties

@Component
class RepositoryInitializer @Inject()(accountRepo: AccountRepository, peerRepo: PeerRepository,
																			trackRepo: TrackRepository, songRecognitionRepo: SongRecognitionRepository) {

	@PostConstruct def initialize() {
		// Accounts
		val account = Account(Properties.userName, "secret", new AtomicLong(WELCOME_CREDITS))
		accountRepo.save(account)
		for (i <- 1 to 9) {
			val a = accountRepo.save(Account(s"demo$i", "secret", new AtomicLong(WELCOME_CREDITS)))
			peerRepo.save(Peer(UUID.randomUUID, a, null, 0L, false))
		}


		// Peers
		if (CONFIG_FILE_PEER.isFile) {
			val peerIds = Source.fromFile(CONFIG_FILE_PEER).getLines().filter(_ contains "peerId")
			for (line <- peerIds) {
				val peerId = line.replaceFirst(".*[:=][^0-9a-f]+([^\"]+).*", "$1")
				peerRepo.save(Peer(UUID fromString peerId, account, HostAndPort fromParts("localhost", 0), 0, false))
			}
		}


		val metadata1 = TrackMetadata("A Bad Kitty", "Henry Jackman", "Puss in Boots")
		trackRepo.save(TrackMetadata("Nothing Else Matters", "Metallica", TrackInfo.unknownTrack.album))
		trackRepo.save(metadata1)


		// Song Recognitions
		songRecognitionRepo.save(SongRecognition(metadata1))
	}

}
